package com.hanscan.persistence.controllers;


import com.hanscan.persistence.EntityManagerSingleton;
import com.hanscan.persistence.controllers.exceptions.MacNullException;
import com.hanscan.persistence.controllers.exceptions.NonexistentEntityException;
import com.hanscan.persistence.controllers.exceptions.PreexistingEntityException;
import com.hanscan.persistence.entities.Terminal;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;


public class TerminalJpaController implements Serializable
{

    public TerminalJpaController()
    {
    }

    public EntityManager getEntityManager()
    {
        return EntityManagerSingleton.getInstance();
    }

    public void create(Terminal terminal) throws Exception
    {
        if (terminal.getMac() == null)
        {
            throw new MacNullException("mac is null");
        }
        try
        {
            findTerminalByMac(terminal.getMac());
            throw new PreexistingEntityException("terminal nsp: " + terminal.
                    getMac()
                    + " already exists in data base");

        }
        catch (NonexistentEntityException ex)
        {
            EntityManager em = null;
            try
            {
                em = getEntityManager();
                em.getTransaction().begin();
                em.persist(terminal);
                em.getTransaction().commit();
            }
            catch (Exception ex2)
            {
                throw ex2;
            }
        }

    }

    public void edit(Terminal terminal) throws NonexistentEntityException,
            Exception
    {
        if (terminal.getMac() == null)
        {
            throw new MacNullException("mac is null");
        }


        //Comprobamos si ya existe un usuario con ese Nsp y no es él mismo
        try
        {
            Terminal terminalByMac = findTerminalByMac(terminal.getMac());
            if (terminalByMac != null)
            {
                if (!terminalByMac.getTerminalId().equals(terminal.getTerminalId()))
                {
                    throw new PreexistingEntityException("terminal mac: "
                            + terminal.getMac()
                            + " already exists in data base");
                }
            }
        }
        catch (NonexistentEntityException ex)
        {
            //No hacer nada
        }

        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            terminal = em.merge(terminal);
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void destroy(Terminal terminal) throws Exception
    {
        //TODO: comprobaciones
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            em.remove(terminal);
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<Terminal> findTerminalEntities()
    {
        return findTerminalEntities(true, -1, -1);
    }

    public List<Terminal> findTerminalEntities(int maxResults, int firstResult)
    {
        return findTerminalEntities(false, maxResults, firstResult);
    }

    private List<Terminal> findTerminalEntities(boolean all, int maxResults,
            int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createQuery("select object(o) from Terminal as o");
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    public Terminal findTerminal(Long id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Terminal.class, id);
        }
        finally
        {
            em.close();
        }
    }

    public Terminal findTerminalByMac(String mac) throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        Terminal terminal = null;
        mac = mac.toUpperCase();
        try
        {
            Query query = em.createNamedQuery("findTerminalByMac");
            query.setParameter(1, mac);
            terminal = (Terminal) query.getSingleResult();
            return terminal;

        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public Terminal findTerminalByName(String name) throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        Terminal terminal = null;
        name = name.toUpperCase();
        try
        {
            Query query = em.createNamedQuery("findTerminalByMame");
            query.setParameter(1, name);
            terminal = (Terminal) query.getSingleResult();
            return terminal;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public Terminal findTerminalByMacAndCompany(String mac, long id) throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        Terminal terminal = null;
        mac = mac.toUpperCase();
        try
        {
            Query query = em.createNamedQuery("findTerminalByMame");
            query.setParameter(1, mac);
            query.setParameter(2, id);
            terminal = (Terminal) query.getSingleResult();
            return terminal;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public Terminal findTerminalByMameAndCompany(String name, long id) throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        Terminal terminal = null;
        name = name.toUpperCase();
        try
        {
            Query query = em.createNamedQuery("findTerminalByMameAndCompany");
            query.setParameter(1, name);
            query.setParameter(2, id);
            terminal = (Terminal) query.getSingleResult();
            return terminal;

        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public int getTerminalCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createQuery("select count(o) from Terminal as o");
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
